package com.stylefeng.guns.modular.train.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.stylefeng.guns.common.constant.Const;
import com.stylefeng.guns.common.constant.MvcResult;
import com.stylefeng.guns.common.constant.state.IsMenu;
import com.stylefeng.guns.common.persistence.model.*;
import com.stylefeng.guns.common.persistence.model.Dict;
import com.stylefeng.guns.common.persistence.model.Employee;
import com.stylefeng.guns.common.persistence.model.FulltimeTrainRule;
import com.stylefeng.guns.config.excel.ExcelExportStylerImpl;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.base.tips.ErrorTip;
import com.stylefeng.guns.core.base.tips.SuccessTip;
import com.stylefeng.guns.core.util.BeanUtils;
import com.stylefeng.guns.core.util.DateUtil;
import com.stylefeng.guns.modular.system.service.IDictService;
import com.stylefeng.guns.modular.system.service.IFulltimeTrainRuleService;
import com.stylefeng.guns.modular.train.service.IEmployeeService;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.ui.Model;
import org.springframework.beans.factory.annotation.Autowired;
import com.stylefeng.guns.core.log.LogObjectHolder;
import com.stylefeng.guns.modular.train.service.IFulltimeTrainPointsService;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;

/**
 * FulltimeTrainPoints控制器
 *
 * @author fengshuonan
 * @Date 2018-01-02 23:14:40
 */
@Controller
@RequestMapping("/fulltimeTrainPoints")
public class FulltimeTrainPointsController extends BaseController {

    private String PREFIX = "/train/fulltimeTrainPoints/";

    @Autowired
    private IFulltimeTrainPointsService fulltimeTrainPointsService;

    @Autowired
    private IFulltimeTrainRuleService fulltimeTrainRuleService;

    @Autowired
    private IDictService dictService;

    @Autowired
    private IEmployeeService employeeService;

    private static List<FulltimeTrainPoints> REPEAT = new ArrayList<>();

    /**
     * 跳转到FulltimeTrainPoints首页
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "fulltimeTrainPoints.html";
    }

    /**
     * 跳转到添加FulltimeTrainPoints
     */
    @RequestMapping("/fulltimeTrainPoints_add")
    public String fulltimeTrainPointsAdd(Model model) {
        List<Dict> twoLevels = dictService.getChildByCode(Const.DICT_TWO_LEVEL);
        List<Dict> projects =dictService.getChildByCode(Const.DICT_PROJECT_LEVEL);
        List<Dict> checkResults =dictService.getChildByCode(Const.DICT_CHECK_RESULT);
//        List<Dict> testResults =dictService.getChildByCode(Const.DICT_TEST_RESULT);

        model.addAttribute("twoLevels",twoLevels);
        model.addAttribute("projects",projects);
        model.addAttribute("checkResults",checkResults);
//        model.addAttribute("testResults",testResults);
        return PREFIX + "fulltimeTrainPoints_add.html";
    }

    /**
     * 跳转到修改FulltimeTrainPoints
     */
    @RequestMapping("/fulltimeTrainPoints_update/{fulltimeTrainPointsId}")
    public String fulltimeTrainPointsUpdate(@PathVariable String fulltimeTrainPointsId, Model model) {
        List<Dict> twoLevels = dictService.getChildByCode(Const.DICT_TWO_LEVEL);
        List<Dict> projects =dictService.getChildByCode(Const.DICT_PROJECT_LEVEL);
        List<Dict> checkResults =dictService.getChildByCode(Const.DICT_CHECK_RESULT);
//        List<Dict> testResults =dictService.getChildByCode(Const.DICT_TEST_RESULT);

        model.addAttribute("twoLevels",twoLevels);
        model.addAttribute("projects",projects);
        model.addAttribute("checkResults",checkResults);
//        model.addAttribute("testResults",testResults);

        FulltimeTrainPoints fulltimeTrainPoints = fulltimeTrainPointsService.selectById(fulltimeTrainPointsId);
        model.addAttribute("item",fulltimeTrainPoints);
        LogObjectHolder.me().set(fulltimeTrainPoints);
        return PREFIX + "fulltimeTrainPoints_edit.html";
    }

    /**
     * 获取FulltimeTrainPoints列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(Employee employee, Double min, Double max) {
        if(BeanUtils.checkFieldValueNull(employee) && min == null && max == null){
            return fulltimeTrainPointsService.selectList(null);
        }

        EntityWrapper<Employee> wrapper = new EntityWrapper<>();
        wrapper.setEntity(employee);
        List<Employee> employees = employeeService.selectList(wrapper);
        Set<String> empCodes = new HashSet<>();
        employees.forEach(e -> empCodes.add(e.getEmpCode()));

        List<FulltimeTrainPoints> list = new ArrayList<>();
        if(!empCodes.isEmpty()){
            EntityWrapper<FulltimeTrainPoints> nwWrapper = new EntityWrapper<>();
            nwWrapper.in("emp_code",empCodes);

            if(min != null || max != null){
                min = min == null ? 0.0 : min;
                max = max == null ? 9999.0 : max;

                nwWrapper.between("integral",min,max);
            }

            list = fulltimeTrainPointsService.selectList(nwWrapper);
        }

        return list;
    }
    /**
     * 新增FulltimeTrainPoints
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(FulltimeTrainPoints fulltimeTrainPoints) {
        fulltimeTrainPoints.setOriginData(Const.IMPORT_TYPE_SYS);
        fulltimeTrainPoints.setCreateDate(new Date());
        fulltimeTrainPointsService.insert(fulltimeTrainPoints);
        return super.SUCCESS_TIP;
    }

    @RequestMapping(value = "/adds")
    @ResponseBody
    public Object adds(@RequestBody FulltimeTrainPoints[] repeatData) {
        List<FulltimeTrainPoints> fulltimeTrainPointss = Arrays.asList(repeatData);
        Date now = new Date();
        List<FulltimeTrainRule> fulltimeTrainRules = fulltimeTrainRuleService.selectAll();

        Map<Integer,List<FulltimeTrainRule>> fulltimeRuleMap = new HashMap<>();
        for (FulltimeTrainRule fulltimeTrainRule : fulltimeTrainRules) {
            if(fulltimeRuleMap.containsKey(fulltimeTrainRule.getEmpType())){
                List<FulltimeTrainRule> temp = fulltimeRuleMap.get(fulltimeTrainRule.getEmpType());
                temp.add(fulltimeTrainRule);
            }else {
                List<FulltimeTrainRule> temp = new ArrayList<>();
                temp.add(fulltimeTrainRule);
                fulltimeRuleMap.put(fulltimeTrainRule.getEmpType(), temp);
            }
        }
        for (FulltimeTrainPoints fulltimeTrainPoints : fulltimeTrainPointss) {
            fulltimeTrainPoints.setOriginData(Const.IMPORT_TYPE_XML);
            fulltimeTrainPoints.setCreateDate(now);

            try {
                fulltimeTrainRuleService.integralCal(fulltimeTrainPoints,fulltimeRuleMap);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        fulltimeTrainPointsService.insertBatch(fulltimeTrainPointss);

        return super.SUCCESS_TIP;
    }

    /**
     * 删除FulltimeTrainPoints
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestParam String fulltimeTrainPointsId) {
        if(fulltimeTrainPointsId.contains(",")){
            List<String> ids = Arrays.asList(fulltimeTrainPointsId.split(","));
            fulltimeTrainPointsService.deleteBatchIds(ids);
        }else{
            fulltimeTrainPointsService.deleteById(fulltimeTrainPointsId);
        }
        return SUCCESS_TIP;
    }

    /**
     * 修改FulltimeTrainPoints
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public Object update(FulltimeTrainPoints fulltimeTrainPoints) {
        fulltimeTrainPointsService.updateById(fulltimeTrainPoints);
        return super.SUCCESS_TIP;
    }

    /**
     * FulltimeTrainPoints详情
     */
    @RequestMapping(value = "/detail/{fulltimeTrainPointsId}")
    @ResponseBody
    public Object detail(@PathVariable("fulltimeTrainPointsId") String fulltimeTrainPointsId) {
        return fulltimeTrainPointsService.selectById(fulltimeTrainPointsId);
    }


    /**
     * 跳转到导入FulltimeTrainPoints
     */
    @RequestMapping("/fulltimeTrainPoints_import")
    public String fulltimeTrainPointsImport() {
        return PREFIX + "fulltimeTrainPoints_import.html";
    }

    /**
     * 导入FulltimeTrainPoints
     */
    @RequestMapping(value = "/import")
    @ResponseBody
    public Object imports(MultipartHttpServletRequest mutReq) throws Exception {

        ImportParams params = new ImportParams();
        params.setStartRows(0);
        params.setTitleRows(1);
        int count = 2;
        try {
            List<FulltimeTrainPoints> fulltimeTrainPointss = ExcelImportUtil.importExcel(mutReq.getFile("file").getInputStream(), FulltimeTrainPoints.class, params);
            Date now = new Date();

            List<FulltimeTrainRule> fulltimeTrainRules = fulltimeTrainRuleService.selectAll();
            Map<Integer,List<FulltimeTrainRule>> fulltimeRuleMap = new HashMap<>();


            for (FulltimeTrainRule fulltimeTrainRule : fulltimeTrainRules) {
                if(fulltimeRuleMap.containsKey(fulltimeTrainRule.getEmpType())){
                    List<FulltimeTrainRule> temp = fulltimeRuleMap.get(fulltimeTrainRule.getEmpType());
                    temp.add(fulltimeTrainRule);
                }else {
                    List<FulltimeTrainRule> temp = new ArrayList<>();
                    temp.add(fulltimeTrainRule);
                    fulltimeRuleMap.put(fulltimeTrainRule.getEmpType(), temp);
                }
            }

                Map<String, String> nameAndCode = employeeService.getNameAndCode();
                List<FulltimeTrainPoints> noRepeat = new ArrayList<>();
                List<FulltimeTrainPoints> hasNameList = new ArrayList<>();

                for (FulltimeTrainPoints fulltimeTrainPoints : fulltimeTrainPointss) {
                        fulltimeTrainPoints.setOriginData(Const.IMPORT_TYPE_XML);
                        fulltimeTrainPoints.setCreateDate(now);

                        if(StringUtils.isEmpty(fulltimeTrainPoints.getEmpCode())) {
                            //姓名检测
                            if (nameAndCode.containsKey(fulltimeTrainPoints.getEmpName())) {
                                //有该姓名，检测是否重名
                                if (nameAndCode.get(fulltimeTrainPoints.getEmpName()).contains(",")) {
                                    //有重名情况
                                    fulltimeTrainPoints.setEmpCode(Const.DEFAULT_CODE);
                                    REPEAT.add(fulltimeTrainPoints);
                                } else {
                                    //无重名、正常插入
                                    fulltimeTrainPoints.setEmpCode(nameAndCode.get(fulltimeTrainPoints.getEmpName()));
                                    fulltimeTrainRuleService.integralCal(fulltimeTrainPoints,fulltimeRuleMap);
                                    noRepeat.add(fulltimeTrainPoints);
                                }
                            } else {
                                throw new Exception("姓名为 " + fulltimeTrainPoints.getEmpName() + " 在员工管理中不存在!");
                            }
                        }else{
                            fulltimeTrainRuleService.integralCal(fulltimeTrainPoints,fulltimeRuleMap);
                            hasNameList.add(fulltimeTrainPoints);
                        }

                        count++;
                    }
                    //不重复，先插入
                    if(noRepeat.size() > 0){
                        fulltimeTrainPointsService.insertBatch(noRepeat);
                    }
                    if(hasNameList.size() > 0){
                        fulltimeTrainPointsService.insertBatch(hasNameList);
                    }
                    //处理重复数据
                    if(!REPEAT.isEmpty()){
                        MvcResult mvcResult = new MvcResult();
                        mvcResult.setData(REPEAT);

                        return mvcResult;
                    }

            } catch (Exception e) {
                e.getStackTrace();
            return new ErrorTip(400,"第"+ count+"条 " +e.getMessage());
            }

        SuccessTip successTip = super.SUCCESS_TIP;
        successTip.setMessage(String.format("成功插入%d", count-2)  + "条数据");
        return successTip;
    }
    @RequestMapping("/repeat")
    public String repeat(Model model){
        model.addAttribute("repeat", JSON.toJSONString(REPEAT));

        //消费后清空
        REPEAT = new ArrayList<>();
        return PREFIX + "repeat.html";
    }
    /**
     * 计算积分
     * @param hours
     * @return
     */
    @RequestMapping(value = "/integralCal")
    @ResponseBody
    public Object integralCal(Double hours, String empCode){
        MvcResult mvcResult = new MvcResult();
        Integer empType = 0;
        //获取到员工类型
        try {
            Employee employee = employeeService.selectByCode(empCode);
            empType = employee.getPostType() == null ? 1 : Integer.parseInt(employee.getPostType());
        }catch (Exception e){
            return new ErrorTip(500,"请检查该员工岗位类型是否设置或与员工编号是否重复！");
        }

        //根据员工类型计算规则
        mvcResult.setData(fulltimeTrainRuleService.integralCal(hours, empType));
        mvcResult.setState("200");

        return mvcResult;
    }


    @RequestMapping(value = "/checkDate")
    @ResponseBody
    public Object checkDate(String empCode, String startDate, String id){
        MvcResult mvcResult = new MvcResult();
        int size = 0;
        EntityWrapper<FulltimeTrainPoints> nwWrapper = new EntityWrapper<>();
        if(!StringUtils.isEmpty(id)){
            //更新时判断日期是否修改,如果日期和原有一致正常保存
            FulltimeTrainPoints fulltimeTrainPoints = fulltimeTrainPointsService.selectById(id);
            if(fulltimeTrainPoints.getStartTime() != null){
                String formatDate = Const.df.format(fulltimeTrainPoints.getStartTime());
                if(startDate.equals(formatDate)){
                    mvcResult.setCode("200");
                    mvcResult.setMsg("数据正常");
                    return mvcResult;
                }
            }
        }

        nwWrapper.eq("emp_code",empCode);
        nwWrapper.eq("start_time",startDate);
        List<FulltimeTrainPoints> fulltimeTrainPointss = fulltimeTrainPointsService.selectList(nwWrapper);
        if(fulltimeTrainPointss != null && fulltimeTrainPointss.size() > size){
            mvcResult.setCode("500");
            mvcResult.setMsg("数据重复！ 已有相同的开始日期，请检查数据！");
        }else {
            mvcResult.setCode("200");
            mvcResult.setMsg("数据正常");
        }
        return mvcResult;
    }



    @RequestMapping(value = "/threeLevelName")
    @ResponseBody
    public MvcResult threeLevelName(String twoLevelName){
        List<Dict> byPName = dictService.getByPNameNotTop(twoLevelName);
        MvcResult mvcResult = new MvcResult();
        mvcResult.setData(byPName);
        return mvcResult;
    }

    /**
     * 导出
     */
    @RequestMapping(value = "/export")
    @ResponseBody
    public void export(HttpServletRequest request, HttpServletResponse response) {
        try {
            List<FulltimeTrainPoints> fulltimeTrainPoints= fulltimeTrainPointsService.selectList(null);
            ExportParams exportParams=new ExportParams("脱产培训积分统计表", "脱产培训积分统计表");
            exportParams.setStyle(ExcelExportStylerImpl.class);
            exportParams.setTitleHeight((short)14);
            Workbook workbook = ExcelExportUtil.exportExcel(exportParams, FulltimeTrainPoints.class, fulltimeTrainPoints);
            OutputStream outputStream=response.getOutputStream();
            String fileName="脱产培训积分统计表.xls";
            response.addHeader("Content-Disposition", "attachment; filename=" + new String(fileName.getBytes(),"ISO-8859-1"));
            workbook.write(outputStream);
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
